#include "clfc/clfc.h"
#include "ME2MailAuth.h"

#ifndef _WIN32
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#endif

void ME2MailLog(const char* fmt,unsigned long sz, const char* str) {
	FILE* fp=fopen("/tmp/merry.log", "a+");
	if(fp) {
		fprintf(fp, fmt, sz, str?str:"null");
		fprintf(fp, "\n");
		fclose(fp);
	}
}

#define AUTH_SIZE 156
int ME2MailAuth(int login_type, LPCSTR user, LPCSTR pass, LPSTR TheUserDir, LPSTR size, LPSTR level)
{
	int logged_in = 3;
	struct vqpasswd *tmpvpw;
	char TheUser[AUTH_SIZE];
	char TheDomain[AUTH_SIZE];

	if(parse_email((char*)user, TheUser, TheDomain, AUTH_SIZE) !=0 ) return ME2MAIL_SYNTAX;
	if ((tmpvpw = vauth_getpw(TheUser, TheDomain))==NULL) {
		vclose();
		return ME2MAIL_EMPTY;
	}
	
	if ( vauth_crypt(TheUser, TheDomain, (char*)pass, tmpvpw) != 0 ) {
		vclose();
		return ME2MAIL_DENY;
	}
	
	if(TheUserDir) strcpy( TheUserDir, tmpvpw->pw_dir);

	if ( tmpvpw->pw_gid & SA_ADMIN )
		logged_in = 0;
	else if ((tmpvpw->pw_gid & QA_ADMIN) || strcmp("postmaster", tmpvpw->pw_name)==0)
		logged_in = 1;
	else
		logged_in = 3;

	if(level) snprintf(level, sizeof(level), "%d", logged_in);
	vclose();
	
	return ME2MAIL_OK;
}

char* ME2MailDomainPath(const char* user) {
	return vget_assign(strchr(user, '@')+1,NULL,0,NULL,NULL);
}
int ME2MailChangePsw(const char* name, const char* domain, const char* newpass) {
	return vpasswd((char*)name, (char*)domain, (char*)newpass, USE_POP);
}

